using System.Collections.Generic;
using System.Data;
using UnityEditor;
using UnityEngine;


[CustomEditor(typeof(IconDataManager))]
public class IconDataManagerInspector : Editor
{
    IconDataManager _target;
    public IconDataManager Target { get { return _target ?? (_target = (IconDataManager)target); } }
    List<IconData> _dataList { get { return ReflectionTools.GetNonPublicField<List<IconData>>(Target, "_dataList"); } }
    static HashSet<int> _isFoldList = new HashSet<int>();


    /// <summary> 更新是否展开某个数据 </summary>
    void UpdateFoldout(int index, bool isFold)
    {
        if (isFold) { _isFoldList.Add(index); }
        else { _isFoldList.Remove(index); }
    }


    /// <summary> 数据对象的UI </summary>
    static void OnDataUI(IconData data)
    {
        ReflectionTools.SetNonPublicField(data, "_ID", EditorGUILayout.IntField("IconID", ReflectionTools.GetNonPublicField<int>(data, "_ID")));
        ReflectionTools.SetNonPublicField(data, "_ResName", EditorGUILayout.TextField("Icon资源名", ReflectionTools.GetNonPublicField<string>(data, "_ResName")));
        ReflectionTools.SetNonPublicField(data, "_Type", EditorGUILayout.EnumPopup("图标类型", ReflectionTools.GetNonPublicField<IconType>(data, "_Type")));
        ReflectionTools.SetNonPublicField(data, "_Pos", EditorGUILayout.Vector2Field("图片位置", ReflectionTools.GetNonPublicField<Vector2>(data, "_Pos")));
        ReflectionTools.SetNonPublicField(data, "_Wpos", EditorGUILayout.Vector3Field("图片世界位置", ReflectionTools.GetNonPublicField<Vector3>(data, "_Wpos")));

        if (null == data.PropSet) ReflectionTools.SetNonPublicField(data, "_PropSet", new PropSet());

        if ((data.PropSet[0] = (EditorGUILayout.Foldout(data.PropSet[0] != 0, "属性信息(PropSet)") ? 1f : 0f)) != 0)
        {
            for (int i = 1; i < data.PropSet.Count; ++i)
            {
                data.PropSet[i] = EditorGUILayout.FloatField(((PropType)i).ToString(), data.PropSet[i]);
            }
        }

    }


    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();
        Target.initializedDataMap = false;
        EditorGUILayout.BeginVertical("Box");
        EditorGUILayout.LabelField("IconDataManager");
        if (GUILayout.Button("添加一个对象")) { Add(); GUI.changed = true; }
        if (GUILayout.Button("清除数据")) { ClearDatas(); GUI.changed = true; }
        EditorGUILayout.Space();
        if (GUILayout.Button("导入数据")) { Load(); GUI.changed = true; }
        if (GUILayout.Button("导出数据")) { ExportDatas(); GUI.changed = true; }
        EditorGUILayout.EndVertical();
        int deleteIndex = -1;

        for (int i = 0, iMax = _dataList.Count; i < iMax; ++i)
        {
            IconData data = _dataList[i];

            EditorGUILayout.BeginVertical("Box");
            {
                EditorGUI.indentLevel = 1;

                EditorGUILayout.BeginHorizontal();
                {
                    // 标题区
                    UpdateFoldout(i, EditorGUILayout.Foldout(_isFoldList.Contains(i), ReflectionTools.GetNonPublicField<int>(data, "_ID").ToString()));
                    // 删除按钮
                    if (GUILayout.Button("X", GUILayout.Width(20))) { deleteIndex = i; }
                }
                EditorGUILayout.EndHorizontal();

                if (_isFoldList.Contains(i))
                {
                    EditorGUILayout.BeginVertical("Box");
                    {
                        OnDataUI(data);
                    }
                    EditorGUILayout.EndVertical();
                }
            }
            EditorGUILayout.EndVertical();
        }

        if (GUI.changed)
        {
            // 去除己删除的对象
            if (deleteIndex >= 0 && deleteIndex < _dataList.Count)
            {
                _isFoldList.Remove(deleteIndex);
                _dataList.RemoveAt(deleteIndex);
            }

            // 保存信息
            EditorUtility.SetDirty(Target);
            GUI.changed = false;
        }
    }


    /// <summary> 添加一个对象 </summary>
    void Add()
    {
        AddDataWindow window = EditorWindow.GetWindow(typeof(AddDataWindow)) as AddDataWindow;
        IconData data = new IconData();

        window.SetGUI<IconData>(() =>
        {
            bool isError = !data.ID.IsValid() || Target.Contains(data.ID);
            OnDataUI(data);

            GUIStyle style = new GUIStyle(GUI.skin.button);
            style.normal.textColor = isError ? Color.red : Color.white;

            if (GUILayout.Button(isError ? "ID无效或重复" : "添加数据", style) && !isError)
            {
                window.Close();
                _dataList.Add(data);
            }
        });
    }


    /// <summary> 清除数据 </summary>
    void ClearDatas()
    {
        if (EditorUtility.DisplayDialog("清除数据（清除后数据无法找回）", "确定要清除所有数据？", "确定", "取消"))
        {
            _dataList.Clear();
            _isFoldList.Clear();
        }
    }


    /// <summary> 确定是否导入Excel </summary>
    void Load()
    {
        if (EditorUtility.DisplayDialog("导入数据（导入后己编辑的数据无法找回）", "确定要导入该路径表内数据？\n" + ExcelTools.ExcelFilesPath + "/Icon.xlsx", "确定", "取消"))
        {
            LoadExcel();
        }
    }


    /// <summary> 直接导入Excel </summary>
    void LoadExcel()
    {
        DataTable sheet = ExcelTools.GetSheet(ExcelTools.ExcelFilesPath + "/Icon.xlsx");
        if (null == sheet) { return; }
        _dataList.Clear();
        ExcelReader eReader = new ExcelReader(sheet);

        for (int i = 4, iMax = eReader.GetRowCount(); i < iMax; ++i)
        {
            string id = eReader.GetData(i, "ID");

            // 表中间有ID无效就直接跳出训话
            if (!id.IsValid())
            {
                Debug.LogError("表ID有无效值， 请检查表：Icon");
                EditorUtility.DisplayDialog("导入表格错误", "表ID有无效值， 请检查表：Icon", "确定");
                break;
            }

            IconData lIconData = IconData.CreateData(
                    eReader.GetData(i, "ID").SafeToInt(), // IconID
                    eReader.GetData(i, "ResName"), // Icon资源名
                    (IconType)(eReader.GetData(i, "Type").SafeToInt()), // 图标类型
                    eReader.GetData(i, "Pos").SafeToVector2(), // 图片位置
                    eReader.GetData(i, "Wpos").SafeToVector3(), // 图片世界位置
                    PropSet.AnalysisStr(eReader.GetData(i, "PropSet")) // 属性信息
                );

            _dataList.Add(lIconData);
        }
    }


    /// <summary> 导出 </summary>
    void ExportDatas()
    {
        string path = Application.dataPath + "/.ExportTabExcle";
        if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); }
        System.IO.StreamWriter sw = new System.IO.StreamWriter(path + "/Icon.txt");
        sw.WriteLine("IconID\tIcon资源名\t图标类型\t图片位置\t图片世界位置\t属性信息");
        sw.WriteLine("int\tstring\tIconType\tVector2\tVector3\tPropSet");
        sw.WriteLine("C\tC\tC\tC\tC\tC");
        sw.WriteLine("ID\tResName\tType\tPos\tWpos\tPropSet");

        for (int i = 0, iMax = _dataList.Count; i < iMax; ++i)
        {
            var data = _dataList[i];

            if (EditorUtility.DisplayCancelableProgressBar("导出：" + Application.dataPath + "/Icon.txt", "ID = " + data.ID, (float)(i + 1) / iMax))
            {
                break;
            }

            sw.WriteLine((data.ID).ToString()+ "\t" +(data.ResName).ToString()+ "\t" +((int)data.Type).ToString()+ "\t" +data.Pos.x + "," + data.Pos.y+ "\t" +data.Wpos.x + "," + data.Wpos.y + "," + data.Wpos.z+ "\t" +data.PropSet.ToString());

        }

        // 关闭文本
        sw.Close();
        // 清除进度条
        EditorUtility.ClearProgressBar();
        // 刷新资源面板显示
        AssetDatabase.Refresh();
    }
}
